package com.dh.convert.rule.function;

import java.net.InetAddress;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorString;

public class GetNoFunction extends AbstractFunction {
	
	private final static AtomicInteger value = new AtomicInteger(100000);
	private  static String num ;
	 static{
	        
	        try {
	           num = InetAddress.getLocalHost().getHostAddress().split("\\.")[3];
	        } catch (Exception e) {
	            num = String.valueOf(new Random().nextInt(9));
	        }
	    }
	 
	    public static int incrementAndGet() {
	        for (;;) {
	            int current = get();
	            int next = current==999999?100000:current + 1;
	            if (compareAndSet(current, next))
	                return next;
	        }
	    }
	    
	    public static int get() {
	        return value.get();
	    }
 

 
    public static boolean compareAndSet(final int current, final int next) {
        if (value.compareAndSet(current, next)) {
            return true;
        } else {
            LockSupport.parkNanos(1L);
            return false;
        }
    }

	/**
	 * 获取序列数
	 * 
	 * @return
	 */
	public static String getSerialNum() {
		return "" + System.currentTimeMillis() + num + incrementAndGet();
	}

	  @Override
	    public AviatorString call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {
		  Object pre = arg1.getValue(env);
		  Object post = arg2.getValue(env);
	     return new AviatorString((pre == null?"":pre) + getSerialNum() + (post ==null?"":post));
	    }
	  @Override
	    public AviatorString call(Map<String, Object> env) {
	     return new AviatorString(getSerialNum());
	    }
	  
	@Override
	public String getName() {
		return "getNo";
	}

}
